<style lang="less">
@import "./commProductManage.less";
</style>
<template>
    <div class="search" style="background-color:white" id="pop">
        <template>
          <Form ref="commProductDetailForm" :model="commProductDetailForm" :label-width="110" :rules="commProductDetailFormValidate" >
             <Tabs type="card">
                <TabPane label="通用产品信息" style="border-left: 1px solid #dddee1;">
                  <div style="overflow:hidden;">
                    <div style="width: 500px;float:left">
                      <Form-item label="通用产品名称:" prop="itemName" style="padding-top:16px;">
                        <Input type="text" v-model="commProductDetailForm.itemName" clearable placeholder="请输入通用产品名称" style="width: 400px"/>
                      </Form-item>
                      <Form-item label="产品卖点:" prop="sellPoint">
                        <Input type="text" v-model="commProductDetailForm.sellPoint" clearable placeholder="请输入产品卖点" style="width: 400px"/>
                      </Form-item>
                      <Form-item label="价格:" prop="itemPrice">
                        <Input type="text" v-model="commProductDetailForm.itemPrice" clearable style="width: 200px"/>
                      </Form-item>

                      <Form-item label="所属商户:" prop="supplierId">
                        <div>
                          <div style="float:left;margin-right:12px;"><Button icon="android-apps" @click="popSupplierSearchMoadl">选择</Button></div>
                          <div style="display:inline-flex;min-width:80px;">
                            <Tag color="blue" type="dot" :fade="false" style="border-color:#2d8cf0 !important" v-model="commProductDetailForm.supplierId" v-if="currSelectedSupplier">{{currSelectedSupplier.supplierName}}</Tag>
                            <!-- <span style="display:inline-block;width:100px;text-align:center; border:1px solid #e8eaec;color:#515a6e;background: #f7f7f7;">9999</span> -->
                          </div>
                        </div>

                      </Form-item>

                      <Form-item label="封面图片:">
                        <!-- <div class="upload-container">
                          <div class="demo-upload-list" v-for="(item,index) in uploadList" :key="index">
                            <template v-if="item.status === 'finished'">
                                <img :src="item.url">
                                <div class="demo-upload-list-cover">
                                    <Icon type="ios-eye-outline" @click.native="handleView(item.name)"></Icon>
                                    <Icon type="ios-trash-outline" @click.native="handleRemove(item)"></Icon>
                                </div>
                            </template>
                            <template v-else>
                                <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
                            </template>
                          </div>
                          <Upload
                              ref="upload"
                              :show-upload-list="false"
                              :default-file-list="defaultList"
                              :on-success="handleSuccess"
                              :format="['jpg','jpeg','png']"
                              :max-size="2048"
                              :on-format-error="handleFormatError"
                              :on-exceeded-size="handleMaxSize"
                              :before-upload="handleBeforeUpload"
                              multiple
                              type="drag"
                              :action="action"
                              style="display: inline-block;width:58px;">
                              <div style="width: 58px;height:58px;line-height: 58px;">
                                  <Icon type="camera" size="20"></Icon>
                              </div>
                          </Upload>
                          <Modal title="View Image" v-model="visible">
                              <img :src="imageUrl" v-if="visible" style="width: 100%">
                          </Modal>
                        </div> -->

                        <image-component
                          ref="commonProductLitpicComp"
                          @on-remove-success="commonProductLitpicRemoveSuccess"
                          @on-add-success="commonProductLitpicAddSuccess">
                        </image-component>
                      </Form-item>

                      <Form-item label="列表图片:">
                        <!-- <div class="upload-container">
                          <div class="demo-upload-list" v-for="(item,index) in uploadList" :key="index">
                            <template v-if="item.status === 'finished'">
                                <img :src="item.url">
                                <div class="demo-upload-list-cover">
                                    <Icon type="ios-eye-outline" @click.native="handleView(item.name)"></Icon>
                                    <Icon type="ios-trash-outline" @click.native="handleRemove(item)"></Icon>
                                </div>
                            </template>
                            <template v-else>
                                <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
                            </template>
                          </div>
                          <Upload
                              ref="upload"
                              :show-upload-list="false"
                              :default-file-list="defaultList"
                              :on-success="handleSuccess"
                              :format="['jpg','jpeg','png']"
                              :max-size="2048"
                              :on-format-error="handleFormatError"
                              :on-exceeded-size="handleMaxSize"
                              :before-upload="handleBeforeUpload"
                              multiple
                              type="drag"
                              action="//jsonplaceholder.typicode.com/posts/"
                              style="display: inline-block;width:58px;">
                              <div style="width: 58px;height:58px;line-height: 58px;">
                                  <Icon type="camera" size="20"></Icon>
                              </div>
                          </Upload>
                          <Modal title="View Image" v-model="visible">
                              <img :src="'https://o5wwk8baw.qnssl.com/' + imgName + '/large'" v-if="visible" style="width: 100%">
                          </Modal>
                        </div> -->
                        <!-- <image-component></image-component> -->
                        <image-component
                          ref="commonProductPiclistComp"
                          @on-remove-success="commonProductPiclistRemoveSuccess"
                          @on-add-success="commonProductPiclistAddSuccess">
                        </image-component>
                      </Form-item>

                      <Form-item label="产品描述:" prop="itemDesc">
                        <textarea v-model="commProductDetailForm.itemDesc" style="width:400px;height:120px;resize:none;line-height:2.0;border:1px solid #dddee1;"/>
                      </Form-item>

                    </div>

                    <hr style="border-bottom:1px solid #dddee1; height:1px;">

                 </div>
                </TabPane>
            </Tabs>

            <hr style="border-bottom:1px solid #dddee1; height:1px;">
          </Form>

          <div style="padding:16px 0px;margin-left:2px;" class="operation">
            <Button @click="cancelSubmitCommProduct" icon="android-arrow-back" style="width:120px;margin-right:10px;">返回主页</Button>
            <!-- <Button :loading="submitLoading" @click="submitHotel" type="primary" :icon="hotelButtonTypeIcon" style="width:120px;">{{hotelButtonTypeText}}</Button> -->
            <Button :loading="submitLoading" @click="submitCommProduct" type="primary" :icon="commProdcutButtonTypeIcon" style="width:120px;">{{commProductButtonTypeText}}</Button>

          </div>

          <supplier-search-comp ref="supplierSearchModal" @on-selected='selectedSupplier'></supplier-search-comp>

      </template>
    </div>
</template>

<script>

import dateFormatUtil from "@/utils/dateFormatUtil";
import tinymce from 'tinymce';

import ImageComponent from "./imageComponent.vue"
import SupplierSearchComp from "./supplierSearchComp.vue"

export default {
  name: "commproduct-detail",
  components: {
    ImageComponent,
    SupplierSearchComp
  },
  data() {
    const validateMobile = (rule, value, callback) => {
      var reg = /^[1][3,4,5,7,8][0-9]{9}$/;
      if (!reg.test(value)) {
        callback(new Error("手机号格式错误"));
      } else {
        callback();
      }
    };
    const validateItemNameNoBlank = (rule, value, callback) => {
      var validObj = rule.validObj;
      var reg = new RegExp(validObj.regexp);
      if (reg.test(value)) {
        callback(new Error(validObj.msg));
      } else {
        callback();
      }
    };
    return {
      loading: true,
      commProductDetailForm: {
        itemName: "",
        itemPrice: "",
        supplierId: "",
        sellPoint: "",
        itemDesc: "",
        litpic: "", //封面图片
        piclist: "" //图片列表
      },
      commProductDetailModalType: 0,
      commProductButtonTypeText: "添加",
      commProdcutButtonTypeIcon: "plus-round",

      commProductDetailFormValidate: {
        itemName: [
          { required: true, message: "通用商品名称不能为空", trigger: "blur" },
          { max: 64, message: '通用商品名称太长'},
          { validator: validateItemNameNoBlank, validObj:{regexp:/\s+/g,msg:"通用商品名称不允许包含空格"} ,trigger: "blur"}
        ]
        ,
        supplierId:[
           { required: true, message: "供应商不能为空", trigger: "blur" },
        ]
      },
      submitLoading: false,

      currSelectedSupplier:"" //选择组件返回

      //图片模块
      //pictrue-module data start
      ,
      // defaultList: [],
      defaultList: [],
      imgName: '',
      visible: false,
      uploadList: [],
      action: "http://106.15.182.1:80/upload/uploadImg",
      imageBaseUrl: "http://106.15.182.1:80",
      imageUrl: '',
     //pictrue-module data end

    };
  },
  methods: {
    init() {

    },

    resetFormByType: function(type,updateCommProduct){
      console.log(updateCommProduct);
      this.currSelectedSupplier = "";
      if(0 === type){
        this.commProductDetailModalType = 0;
        this.commProductButtonTypeText = "添加";
        this.commProdcutButtonTypeIcon = "plus-round";

        // this.uploadList = [];
        // this.defaultList = [];
        this.$refs.commonProductLitpicComp.initByType("goodsitem",0,null);
        this.$refs.commonProductPiclistComp.initByType("goodsitem",0,null);


      }else if(1 === type){
        this.commProductDetailModalType = 1;
        this.commProductButtonTypeText = "编辑";
        this.commProdcutButtonTypeIcon = "edit";
        this.currSelectedSupplier = updateCommProduct.supplier;
        this.commProductDetailForm = updateCommProduct;

        this.$refs.commonProductLitpicComp.initByType("goodsitem",1,updateCommProduct.litpic);
        this.$refs.commonProductPiclistComp.initByType("goodsitem",1,updateCommProduct.piclist);
        // let echoLitpic = this.echoImages(updateCommProduct.litpic);
        // console.log("=============")
        // console.log(echoLitpic)
        // this.defaultList = echoLitpic;
        // this.uploadList = echoLitpic;
        // // this.$refs.upload.fileList = echoLitpic;

      }else{}

      this.$refs.commProductDetailForm.resetFields();
      for (let attr in this.commProductDetailForm) {
        if (this.commProductDetailForm[attr] == null) {
          this.commProductDetailForm[attr] = "";
        }
      }
    },

    popSupplierSearchMoadl:function(){
      this.$refs.supplierSearchModal.openSupplierSearchModal(true);
    },
    selectedSupplier(res){
      console.log("========selectedSupplier============");

      console.log(res);
      this.currSelectedSupplier = res;
      this.commProductDetailForm.supplierId = res.id;
    },

    submitCommProduct() {
      this.$refs.commProductDetailForm.validate(valid => {
        if (valid) {
          let url = "";
          console.log("=======================");
          if (this.commProductDetailModalType === 1) {
            // 编辑特产
            url = "/goods_item/update";
            this.submitLoading = true;

            // this.commProductDetailForm.litpic = this.uploadFileListToStr(this.$refs.upload.fileList);

            this.putRequest(url, this.commProductDetailForm).then(res => {
              this.submitLoading = false;
              if (res.success === true) {
                this.$Message.success("更新操作成功");
                this.$emit('on-commproduct-success',true);
                // this.init();
              }
            });
          }else{
            url = "/goods_item/create";
            this.submitLoading = true;
            var createCommProduct = this.commProductDetailForm;
            if(createCommProduct.id) delete createCommProduct.id;
            this.postRequest(url, createCommProduct).then(res => {
              this.submitLoading = false;
              if (res.success === true) {
                this.$Message.success("操作成功");
                this.$emit('on-commproduct-success',true);
              }
            });
          }

        }
      });
    },
    cancelSubmitCommProduct:function(){
      this.$emit('on-commproduct-cancel',true);
    }

    ,
    commonProductLitpicRemoveSuccess:function(res){
      console.log('==commonProductLitpicRemoveSuccess==');
      console.log(res);
      if(res.flag){
        this.commProductDetailForm.litpic = res.pathStr;
      }
    },
    commonProductLitpicAddSuccess:function(res){
      console.log('==commonProductLitpicAddSuccess==');
      console.log(res);
      if(res.flag){
        this.commProductDetailForm.litpic = res.pathStr;
      }
    },
    commonProductPiclistRemoveSuccess:function(res){
      console.log('==commonProductPiclistRemoveSuccess==');
      console.log(res);
      if(res.flag){
        this.commProductDetailForm.piclist = res.pathStr;
      }
    },
    commonProductPiclistAddSuccess:function(res){
      console.log('==commonProductPiclistAddSuccess==');
      console.log(res);
      if(res.flag){
        this.commProductDetailForm.piclist = res.pathStr;
      }
    }


    //picture methods start
    ,
    handleView (name) {
      this.imageUrl = this.imageBaseUrl+'/upload/'+name;
      this.visible = true;
    },
    handleRemove (file) {
      console.log("========handleRemove========");
      console.log(file);
      const fileList = this.$refs.upload.fileList;
      this.$refs.upload.fileList.splice(fileList.indexOf(file), 1);

      this.uploadList = this.$refs.upload.fileList;
    },
    handleSuccess (res, file) {
      console.log("===============上传成功===============");
      console.log(res);
      console.log(file);
      if(res.success === true){
        let returnImg = res.result;
        let pathArr = returnImg.relativePaths.split('/');
        let pathLastStr = pathArr[pathArr.length-1];

        file.url = this.imageBaseUrl+ returnImg.relativePaths;
        file.name = pathLastStr;

        // this.$refs.upload.fileList.forEach(function(item){
        //   console.log(item);
        //   item.showProgress = true;
        // })

        this.uploadList = this.$refs.upload.fileList;
        // //bug 最后一个有时会是showProgress=false
      }
    },
    handleFormatError (file) {
      this.$Modal.warning({
          title: "上传文件格式错误提示窗口",
          content: file.name + ' 文件格式不正确，请选择jpg或者png文件'
      });
    },
    handleMaxSize (file) {
      this.$Modal.warning({
          title: "上传文件过大提示窗口",
          content: file.name + ' 文件太大，不能超过2M'
      });
    },
    handleBeforeUpload () {
      console.log(this.uploadList);
      console.log(this.$refs.upload.fileList);

      const check = this.uploadList.length < 5;
      if (!check) {
          this.$Modal.warning({
            title: "上传文件过多提示窗口",
            content: ' 最多上传5张图片'
        });

      }
      return check;
    }
     //picture methods end

    ,
    uploadFileListToStr(uploadList) {
      var uploadListStr = "";
      uploadList.forEach(function(item){
        let itemPathStr = item.response.result.relativePaths+",";
        uploadListStr += itemPathStr;
      })
      if("" !== uploadListStr){
        uploadListStr = uploadListStr.substring(0,uploadListStr.length-1); //去除最后一个逗号
      }
        return uploadListStr;
    },

    //编辑时图片回显(逗号字符串封装成对象)
    echoImages(imageUrlStr){
      if(null===imageUrlStr || ""===imageUrlStr){
        return [];
      }
      let imageUrlArr = imageUrlStr.split(',');
      var echoImagesArr = [];
      imageUrlArr.forEach(function(item){
        let pathArr = item.split('/');
        let pathLastStr = pathArr[pathArr.length-1];
        echoImagesArr.push({
          status: 'finished',
          name: pathLastStr,
          url: 'http://localhost:9080' + item
        })
      })

      return echoImagesArr;
    }


  },
  mounted() {
    this.init();

    //picture mounted start
    // console.log("============mounted=============")
    // this.uploadList = this.$refs.upload.fileList;
    //picture mounted end
  }
};
</script>
